package cn.virens.web.components.spring;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtil {

	/**
	 * 如果 bean 是 ApplicationContextAware 的实现类，就将ApplicationContext 注入
	 * 
	 * @param  <E>                bean's type
	 * @param  bean               bean
	 * @param  applicationContext applicationContext
	 * @throws BeansException     注入异常
	 */
	public static <E> void inject(E bean, ApplicationContext applicationContext) throws BeansException {
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(applicationContext);
		} else if (bean instanceof Iterable<?>) {
			for (Object _bean : (Iterable<?>) bean) {
				ApplicationContextUtil.inject(_bean, applicationContext);
			}
		} else if (bean instanceof Map<?, ?>) {
			for (Object _bean : ((Map<?, ?>) bean).values()) {
				ApplicationContextUtil.inject(_bean, applicationContext);
			}
		}
	}

	/**
	 * 如果 bean 是 InitializingBean 的实现类，就将调用afterPropertiesSet
	 * 
	 * @param  <E>       bean's type
	 * @param  bean      bean
	 * @throws Exception 初始化异常
	 */
	public static <E> void init(E bean) throws Exception {
		if (bean instanceof InitializingBean) {
			((InitializingBean) bean).afterPropertiesSet();
		} else if (bean instanceof Iterable<?>) {
			for (Object _bean : (Iterable<?>) bean) {
				ApplicationContextUtil.init(_bean);
			}
		} else if (bean instanceof Map<?, ?>) {
			for (Object _bean : ((Map<?, ?>) bean).values()) {
				ApplicationContextUtil.init(_bean);
			}
		}
	}
}
